package com.lzp.java.concurrent.jmm.synchronize;

/**
 * 同步方法中调用非同步public方法--每个线程通过A调用B方法，线程安全。
 */
public class SynchronizedMethodContainNo2 implements Runnable {
    private static SynchronizedMethodContainNo2 instance = new SynchronizedMethodContainNo2();

    @Override
    public void run() {
        if ("Thread-0".equals(Thread.currentThread().getName())) {
            method1();
        } else {
            method1();
        }
    }

    public synchronized void method1() {
        System.out.println("加锁方法，当前线程" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
            method2();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程结束" + Thread.currentThread().getName());
    }

    private void method2() {
        System.out.println("未加锁方法，当前线程" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程结束" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        /* 死循环等待线程结束*/
        while (t1.isAlive() || t2.isAlive()) {
        }
    }
}
